package com.zzx.boot.exception;

import com.zzx.boot.utils.R;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;


/**
 * @author tan
 * @version 1.0
 * @date 2023/7/7 20:12
 */
@RestControllerAdvice
public class GlobalControllerAdvice {


    @ExceptionHandler(value = {AccessDeniedException.class, AuthenticationException.class})
    public R securityError(RuntimeException e){
        throw e;
    }


    @ExceptionHandler(value = {MethodArgumentNotValidException.class,BindException.class})
    public R validException(MethodArgumentNotValidException e){
        String table = e.getFieldError().getObjectName();
        String field = e.getFieldError().getField();
        String message = e.getFieldError().getDefaultMessage();

        return R.error(752,table+"."+field+":  "+message);
    }


    @ExceptionHandler(value = {SystemctlException.class})
    public R systemctException(SystemctlException e){
        return R.error(e.getCode(),e.getMessage());
    }


    @ExceptionHandler(value = {Exception.class})
    public R systemctlException(Exception e){
        return R.error(999,e.getMessage());
    }

}
